package com.carrental.rental.controller;

import com.carrental.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 订单价格计算控制器
 */
@Slf4j
@Api(tags = "订单价格计算接口")
@RestController
@RequestMapping("/order")
@RequiredArgsConstructor
public class OrderCalculateController {

    @ApiOperation("价格计算")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "vehicleId", value = "车辆ID", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "开始日期", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "结束日期", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping("/calculate")
    public Result<Map<String, Object>> calculate(
            @RequestParam Long vehicleId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {

        log.info("计算价格，车辆ID：{}，开始日期：{}，结束日期：{}", vehicleId, startDate, endDate);

        try {
            // 计算租期天数
            long days = ChronoUnit.DAYS.between(startDate, endDate) + 1; // 包含结束日期

            // 获取车辆日租金（这里使用模拟价格）
            BigDecimal dailyPrice = getDailyPrice(vehicleId);

            // 计算租金总额
            BigDecimal rentalAmount = dailyPrice.multiply(new BigDecimal(days));

            // 计算服务费（假设为租金的10%，最低50元）
            BigDecimal serviceFee = rentalAmount.multiply(new BigDecimal("0.1"));
            if (serviceFee.compareTo(new BigDecimal(50)) < 0) {
                serviceFee = new BigDecimal(50);
            }

            // 计算总价（租金+服务费）
            BigDecimal totalAmount = rentalAmount.add(serviceFee);

            // 计算押金（假设为租金的50%，最低2000元）
            BigDecimal deposit = rentalAmount.multiply(new BigDecimal("0.5"));
            if (deposit.compareTo(new BigDecimal(2000)) < 0) {
                deposit = new BigDecimal(2000);
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("vehicleId", vehicleId);
            result.put("startDate", startDate.toString());
            result.put("endDate", endDate.toString());
            result.put("days", days);
            result.put("dailyPrice", dailyPrice);
            result.put("rentalAmount", rentalAmount);
            result.put("serviceFee", serviceFee);
            result.put("totalAmount", totalAmount);
            result.put("deposit", deposit);

            return Result.success(result);
        } catch (Exception e) {
            log.error("计算价格失败", e);
            return Result.error("计算价格失败：" + e.getMessage());
        }
    }

    /**
     * 获取车辆日租金（模拟）
     * 
     * @param vehicleId 车辆ID
     * @return 日租金
     */
    private BigDecimal getDailyPrice(Long vehicleId) {
        // 为简化实现，这里根据车辆ID生成一个随机价格
        Random random = new Random(vehicleId);
        int basePrice = 200 + random.nextInt(800); // 200-1000元之间的随机价格
        return new BigDecimal(basePrice);
    }
}